/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable @typescript-eslint/no-unused-vars */
import CustomBlockquote from "@/components/Blockquote";
import CustomerTable from "@/components/CustomerTable";
import { ExclamationCircleFilled, PlusOutlined } from "@ant-design/icons";
import { ActionType, PageContainer, ProColumns } from "@ant-design/pro-components";
import { Button, Divider, Dropdown, FormInstance, Image, Input, Modal, Popconfirm, Space, Typography, message } from "antd";
import React, { useEffect, useRef, useState } from "react";
import TenantForm, { TenantFormData } from "./components/TenantForm";
import { getDict } from "@/services/api/module/system/dict";
import { getPageList, remove, save, update } from "@/services/api/module/tenant/tenant/tenants";
import FilterDrawer from "@/components/FilterDrawer";
import ImportExportDropdown from "@/components/ImportExportDropdown";
import { useNavigate } from "react-router-dom";
import { createTableColumns, pagination } from "./constants";
import UpdateTenantForm, { TenantFormData as UpdateTenantFormData } from "./components/UpdateTenantForm";
import { dict } from "@/utils/DictionaryCacheManager";
const { confirm } = Modal;
const UserTableList: React.FC = () => {
	const navigate = useNavigate();
	const formTableRef = useRef<FormInstance>();
	const actionRef = useRef<ActionType>();
	const [selectedRows, setSelectedRows] = useState<any>([]);
	const [industryOptions, setIndustryOptions] = useState<any>([]);
	const [scaleOptions, setScaleOptions] = useState<any>([]);
	const [formOpen, setFormOpen] = useState<boolean>(false);
	const [currentId, setCurrentId] = useState<undefined | number>(undefined);
	const [updateFormOpen, setUpdateFormOpen] = useState<boolean>(false);
	const [statusOptions, setStatusOptions] = useState<any>([]);
	const [searchFormValue, setSearchFormValue] = useState<any>(undefined);
	const [searchValue, setSearchValue] = useState<any>(undefined);
	useEffect(() => {
		// dict.getDict("sys_normal_disable");
		dict.getDict("sys_normal_disable").then(data => {
			setStatusOptions(data);
		});
		dict.getDict("company_scale").then(data => {
			setScaleOptions(data);
		});
		dict.getDict("company_industry").then(data => {
			setIndustryOptions(data);
		});
	}, []);
	// 关闭表单刷新列表
	const handleTableForm = async () => {
		setUpdateFormOpen(false);
		setCurrentId(undefined);
		actionRef?.current?.reload();
	};
	const handleAddClick = async () => {};
	// 关闭表单刷新列表
	const handleCloseForm = async () => {
		setFormOpen(false);
		setCurrentId(undefined);
	};
	const handleRefreshTable = () => {
		if (actionRef.current) {
			actionRef.current.reload();
		}
	};
	const handleColumnEditor = (record: any) => {
		setCurrentId(record.id);
		setUpdateFormOpen(true);
	};
	const handleColumnRemove = (record: any) => {
		handleRemove(record?.id);
	};
	const handleColumnAsync = () => {};
	const handleColumnDetails = (record: any) => {
		navigate("/app/system/tenant/tenantDetail", {
			state: {
				id: record?.id
			}
		});
		// setDataSource(record);
		// setDetailsOpen(true);
		// navigator("/system/tenant/tenant/TenantDetails", {
		// 	state: {
		// 		id: record?.id
		// 	}
		// });
	};
	const columns = createTableColumns(
		statusOptions,
		handleColumnEditor,
		handleColumnRemove,
		handleColumnAsync,
		handleColumnDetails
	);
	// 删除
	const handleRemove = async (ids: number | Array<number>) => {
		return new Promise((reslove, reject) => {
			remove(ids)
				.then((res: any) => {
					message.success(res.msg);
					if (actionRef.current) {
						actionRef.current.reload();
					}
					reslove(true);
				})
				.catch(() => {
					reject(true);
				});
		});
	};

	// 删除警告提示
	const showRemoveConfirm = (ids: Array<number>, names: Array<string>) => {
		confirm({
			title: "警告",
			icon: <ExclamationCircleFilled />,
			content: <div>您确定要删除租户名为“{names}”吗？执行此操作后，相关数据将被永久删除，无法恢复。</div>,
			onOk() {
				return handleRemove(ids);
			},
			onCancel() {}
		});
	};

	const handleExport = (values: any) => {};
	// 編輯
	const handleUpdate = async (values: UpdateTenantFormData) => {
		return new Promise((resolve, reject) => {
			update({ ...values } as UpdateTenantFormData)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};
	//数据请求
	const tableDataRequest = async (params: {} | undefined) => {
		return await getPageList({ ...searchFormValue, ...searchValue }).then((data: any) => {
			return data;
		});
	};
	const handleOnSearch = async (value: any) => {
		setSearchValue({
			userName: value
		});
		actionRef.current?.reload();
	};
	return (
		<>
			<CustomerTable<API.Tenant.TenantVo>
				actionRef={actionRef}
				formRef={formTableRef}
				rowKey="id"
				tableStyle={{ minHeight: "calc(100vh - 200px)" }}
				key="tenantList"
				toolbar={{
					search: (
						<Space>
							<Input.Search placeholder="配置键" allowClear style={{ width: 280 }} onSearch={handleOnSearch} />
							{/* <FilterDrawer
								columns={columns}
								tableActionRef={actionRef}
								onReset={() => {
									setSearchFormValue(undefined);
									actionRef?.current?.reload();
								}}
								onSubmit={(values: any) => {
									setSearchFormValue(values);
									actionRef?.current?.reload();
								}}
							/> */}
						</Space>
					)
				}}
				search={false}
				request={tableDataRequest}
				pagination={pagination}
				columns={columns}
				rowSelection={{
					onChange: (_, selectedRows) => {
						setSelectedRows(selectedRows);
					},
					getCheckboxProps: (record: any) => ({
						disabled: record?.id === 1, // Column configuration not to be checked
						name: record.id
					})
				}}
				tableAlertRender={false}
				// @ts-ignore
				toolBarRender={() => {
					return (
						<>
							<Button type="primary" key="add" onClick={() => setFormOpen(true)}>
								<PlusOutlined />
								创建租户
							</Button>
							{React.useMemo(() => {
								return <ImportExportDropdown key="import" columns={columns} onExport={(values: any) => {}} />;
							}, [])}
							{selectedRows.length > 0 && (
								<Button
									type="primary"
									danger
									key="delete"
									onClick={async () => {
										if (selectedRows.length <= 0) {
											message.warning("请选择一条或多条数据");
											return;
										}
										showRemoveConfirm(
											Array.from(selectedRows, ({ id }) => id),
											Array.from(selectedRows, ({ companyName }) => companyName)
										);
									}}
								>
									批量删除
								</Button>
							)}
						</>
					);
				}}
			/>
			<TenantForm
				scaleOptions={scaleOptions}
				industryOptions={industryOptions}
				statusOptions={statusOptions}
				id={currentId}
				open={formOpen}
				onRefresh={handleRefreshTable}
				onCancel={handleCloseForm}
			/>
			<UpdateTenantForm
				scaleOptions={scaleOptions}
				industryOptions={industryOptions}
				open={updateFormOpen}
				statusOptions={statusOptions}
				id={currentId}
				onCancel={() => {
					setCurrentId(undefined);
					setUpdateFormOpen(false);
				}}
				onSubmit={handleUpdate}
			/>
		</>
	);
};

export default UserTableList;
